<?php

require_once("database.php");

if($_GET and isset($_GET['id']) and is_numeric($_GET['id'])){

  // Sizes
  $xsize = 300;
  $ysize = 300;

  // Days to display
  $days = 10;

  //create blank image
  $img = imagecreatetruecolor($xsize, $ysize);
  $bgcolor = imagecolorallocate($img, 255, 255, 255);
  imagefill($img, 0, 0, $bgcolor);


  $today = time();

  // Get points from database
  $points = array();
  for($i = 0; $i < $days; $i++){
    // Get day boundaries
    $day_min = $today - (($days - $i + 1) * 60 * 60 * 24);
    $day_max = $today - (($days - $i) * 60 * 60 * 24);
    
    // SQL to get the average price for a given day
    $sql = "
      SELECT AVG(price) AS avg_price
      FROM apartment
      WHERE date >= " . $day_min . "
      AND date < " . $day_max . "
      AND city_id = " . sql_escape($_GET['id']);
    
    $prices = query_select($sql);
    $average_price = $prices[0]['avg_price'];
    
    // If average price exists, set the respective point to that price
    if(isset($average_price)){
      $points[$i] = $average_price;
    }
    // If the average price is not set, but it's not the first point, set the
    // respective point to the same value as the previous point
    else if($i != 0){
      $points[$i] = $points[$i-1];
    }
    // Else if the first price is not set (base case), just set it to min value for now
    else {
      $points[$i] = 0.5;
    }
  }

  // Set color
  $info_color = imagecolorallocate($img, 0, 0, 0);
  $guide_color = imagecolorallocate($img, 210, 210, 210);

  if(count($points) > 0){
    // Create lines

    $xmult = $xsize / (sizeof($points) - 1);
    
    if(max($points) > 100.0){
      $ymult = $ysize / max($points);
    }
    else {
      $ymult = $ysize / 100.0;
    }

    // Put in horizontal scale lines
    for($i = 0; $i < $ysize; $i += 500 * $ymult){
      imageline($img, 0, $i, $xsize, $i, $guide_color);
    }
    
    // Put in vertical lines and information lines
    $x2 = 0 * $xmult;
    $y2 = $ysize - $points[0] * $ymult;
    
    for($i=1; $i<sizeof($points); $i++)
    {
      $x1 = $x2;
      $y1 = $y2;
      
      $x2 = $i * $xmult;
      $y2 = $ysize - $points[$i] * $ymult;
      
      // vertical guideline
      imageline($img, $x2, 0, $x2, $ysize, $guide_color);
      
      // info line
      imageline($img, $x1, $y1, $x2, $y2, $info_color);
    }
  }
  else {
    $string = "No data!";
    imagestring($img, 5, $xsize/2 - 50, $ysize/2 - 10, $string, $info_color);
  }

  header("Content-type: image/jpeg");
  imagepng($img);
  imagedestroy($img);
}

?>